<script setup lang='ts'>
import {ref, reactive, PropType, onMounted, computed, watch, onBeforeMount} from 'vue'
import { ElMessage, FormRules} from 'element-plus'
import {FromItem} from '@/components/dFrom/dFrom'
import httpService, { GuideItem, LeftTableDataType, LeftTableDataFormType} from '@/api/physicalExaminationManager/physicalPackage'

import dDialog from '@/components/dDialog/dDialog.vue'

import operation from '@/components//dTable/components/operation.vue'
import {HeaderData, Operation as Opr, RowOperbuttons} from '@/components/dTable/dTable'
import dTable from '@/components/dTable/dTable.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import {ColorRed, ColorTheme, SeleteData} from '@/api/config'
import {transfDicArrData, getObjectByKey} from '@/util/common'
import useStore from '@/store/common'
import { on } from 'events'
const {store} = useStore.setup()


const props = defineProps({
  //显示
  showDialog:{
    type:Boolean,
    required:true
  },
  //数据
  data:{
    type:Object as PropType<LeftTableDataFormType>,
    required:true
  }
})

const emits = defineEmits(['close'])

// const formData = ref({id:null, packageGuideList:[], tips:''})
// const formData = reactive({...props.data})

// const tableData =  ref<Array<GuideItem>>(formData.value.packageGuideList ? [...formData.value.packageGuideList] : [])
// const formData = ref<LeftTableDataType>({...props.data})
const formData = ref<LeftTableDataFormType>({...props.data, packageGuideList:[]})


// 显示加载状态
const showSaveLoading = ref(false)

//表单清除控制
const resetFieldsFlag = ref(false)

//表单验证并提交
const validateFlag = ref(false)

// 确认按钮
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}

//关闭
const onClose = () => {
  emits('close')
  //关闭后清除表单数据以及表单验证数据 可根据具体业务自行调整
  resetFieldsFlag.value = !resetFieldsFlag.value
}

//取消按钮
const onCancel = () => {
  onClose()
}

//表单项
const fromItems = ref<Array<FromItem>>([
  {label:'检前提示', placeholder:'请填写检前提示', prop:'tips', type:'input', inputType:'textarea' },
  {label:'体检指引', prop:'packageGuideList', type:'slot', slotName:'packageGuideList'}
])
// 表单规则
const rules = reactive<FormRules>({
  tips:[
    {required:true, message: '请输入检前提示', trigger: ['change', 'blur']},
    {message:'长度应不超过500个字符', max:500, trigger: ['change', 'blur']}
    // {required:true, message:'应输入汉字、字母、数字、字符', pattern:Normal, trigger:['change', 'blur']}
  ],
  packageGuideList:[
    {required:true, message: '请输入体检指引', trigger: ['change', 'blur']}
  ],
  checkType:[
    {required:true, message: '请选择检查类型', trigger: ['change', 'blur']}
  ],
  deptId:[
    {required:true, message: '请选择科室', trigger: ['change', 'blur']}
  ],
  guideName:[
    {required:true, message: '请填写指引名称', trigger: ['change', 'blur']},
    {message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ],
  itemTips:[
    {required:true, message: '请填写指引提示', trigger: ['change', 'blur']},
    {message:'长度应不超过100个字符', max:100, trigger: ['change', 'blur']}
  ]
})

// 表格数据
// const tableData = ref<Array<GuideItem>>([])
// 表头数据
const tableHeaderData = ref<Array<HeaderData>>([
  {prop: 'checkType', label: '检查类型', columnType: 'slot', 'min-width': '100'},
  {prop: 'deptId', label: '科室名称', columnType: 'slot', 'min-width': '100'},
  {prop: 'guideName', label: '指引名称', columnType: 'slot', 'min-width': '100'},
  {prop: 'tips', label: '指引提示', columnType: 'slot', 'min-width': '100'},
  {prop: 'oper', label: '操作', columnType: 'slot', 'width': '80'}
])

// 删除操作按钮数据
const operationDataDelete: Array<Opr> = [{code: 'delete', label: '删除', iconConfig: {icon: 'common-delete', type: 'custom', color: ColorRed, size: 20}}]
// 新增操作按钮数据
const operationDataAdd: Array<Opr> = [{code: 'add', label: '添加', iconConfig: {icon: 'common-swap-add', type: 'custom', color: ColorTheme, size: 20}}]

const formRef = ref()
// 弹窗保存
const onSubmit = () => {
  const elForm = formRef.value
  if (!elForm) return
  elForm.validate((valid) => {
    if (valid) {
      delete formData.value.oper
      httpService.setGuide(formData.value).then(() => {
        showSaveLoading.value = false
        ElMessage.success('保存成功！')
        emits('close')
      }).catch((error) => {
        showSaveLoading.value = false
        console.warn(error)
      })
    } else {
      return false
    }
  })
}

//添加数据
const baseAdd = {
  packageId:formData.value.id, //	integer	套餐id
  checkType:null, //	integer 检查类型(字典)
  deptId:null, //	integer	 科室名称
  guideName:'',	//string 指引名称
  tips:'', //	string	指引提示
  id:null
}

//添加展示按钮
const showButton = (dataList:Array<GuideItem>) => {
  const returnList:Array<GuideItem & RowOperbuttons> = []
  if (!dataList.length) {
    const newAdd = JSON.parse(JSON.stringify(baseAdd))
    dataList.push(newAdd)
  }
  dataList.map((item, index) => {
    returnList.push({...item, oper:(index === 0 && dataList.length === 1) ?  operationDataAdd : [...operationDataAdd, ...operationDataDelete]})
    // returnList.push({...item, oper:index === (dataList.length - 1) ? [...operationDataAdd, ...operationDataDelete] : operationDataDelete})
  })

  return returnList
}

// 添加事件
const onAdd = (index?:number) => {
  const addData = JSON.parse(JSON.stringify(baseAdd))
  formData.value.packageGuideList?.splice((index || 0) + 1, 0, addData)
  formData.value.packageGuideList = showButton(formData.value?.packageGuideList || [])
}

// 删除事件
const onRemove = (index?: number) => {
  formData.value.packageGuideList?.splice(index || 0, 1)
  formData.value.packageGuideList = showButton(formData.value.packageGuideList || [])
}

// 操作栏点击
const onErtion = (code, row) => {
  if (code === 'delete') {
    onRemove(formData.value.packageGuideList?.indexOf(row))
  } else if (code === 'add') {
    // console.log('row.$index', row.$index)
    onAdd(formData.value.packageGuideList?.indexOf(row))
  }
}

const checkTypeList = ref<Array<SeleteData>>([])
//获取字典
const getDic = () => {
  store.getDicData('check_type').then((res) => {
    checkTypeList.value = transfDicArrData(res)
  })
}

onMounted(() => {
  getDic()
})

const packageGuideList = computed(() => {
  return JSON.parse(JSON.stringify(formData.value.packageGuideList))
})

watch(
  packageGuideList,
  (newValue, oldValue) => {
    newValue.forEach((item, index) => {
      if (item.checkType) {
        if (item.checkType !== oldValue?.[index]?.checkType) {
        // if (item.checkType) {
          httpService.getDept({checkType:item.checkType}).then(res => {
            const deptList = res.data.data
            const currDept = deptList.find(dept => dept.id === item.deptId)
            if (!currDept) {
              formData.value.packageGuideList && (formData.value.packageGuideList[index].deptId = null)
            }
            formData.value.packageGuideList && (formData.value.packageGuideList[index].deptList = deptList.map(item => {
              return {
                label:item.deptName,
                value:item.id
              }
            }))
          })
        // } else {
        //   formData.value.packageGuideList[index].deptId = null
        //   formData.value.packageGuideList[index].deptList = []
        // }
        }
      }
      // else {
      //   formData.value.packageGuideList[index].deptId = null
      //   formData.value.packageGuideList[index].deptList = []
      // }
    })
  },
  {
    deep:true,
    immediate:true
  }
)
onBeforeMount(() => {
  httpService.getGuide(formData.value.id).then(res => {
    formData.value.packageGuideList = res.data.data?.packageGuideList || []
    if (formData.value.packageGuideList.length === 0) {
      onAdd()
    } else {
      formData.value.packageGuideList = showButton(formData.value.packageGuideList)
    }
  })
})

</script>

<template>
  <d-dialog
    title="配置引导单"
    width="800px"
    :show-dialog="showDialog"
    :show-save-loading="showSaveLoading"
    @cancel="onCancel"
    @confirm="onSubmit"
    @close="onClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules">
      <el-form-item label="检前提示" prop="tips" class="common">
        <el-input v-model="formData.tips" type="textarea" />
      </el-form-item>
      <el-form-item label="体检指引" prop="packageGuideList">
        <el-table :data="formData.packageGuideList" style="width: 100%" :border="true">
          <el-table-column v-for="item,index in tableHeaderData" :key="index" :prop="item.prop" :label="item.label" :width="item.width" :min-width="item['min-width']">
            <template #default="scope">
              <el-form-item :prop="`packageGuideList[${scope.$index}].${item.prop}`" :rules="rules[item.prop==='tips'?'itemTips':item.prop]" class="table">
                <el-select v-if="item.prop==='checkType'" v-model="scope.row['checkType']">
                  <el-option v-for="checkTypeItem,checkTypeIndex in checkTypeList" :key="checkTypeIndex" :label="checkTypeItem.label" :value="checkTypeItem.value" />
                </el-select>
                <el-select v-else-if="item.prop==='deptId'" v-model="scope.row['deptId']">
                  <el-option v-for="deptiItem,deptIndex in scope.row['deptList']" :key="deptIndex" :label="deptiItem.label" :value="deptiItem.value" />
                </el-select>
                <operation
                  v-else-if="item.prop==='oper'"
                  :row="scope.row"
                  :col="item"
                  @opertion-click="onErtion"
                />
                <el-input v-else-if="item.prop==='tips'" v-model="scope.row[item.prop]" type="textarea" :rows="1" />
                <el-input v-else v-model="scope.row[item.prop]" />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
  </d-dialog>
</template>

<style scoped lang="less">
.el-form-item.common{
  margin-bottom: 20px;
}
.el-form-item.table{
  margin-bottom: 14px;
  margin-top: 14px;
}

.el-table{
  :deep(.el-table__cell){
    padding: 0;
  }
}

</style>